package com.sixmac.police.controller;

import com.sixmac.common.base.BaseController;
import com.sixmac.core.config.Configue;
import com.sixmac.core.constant.Constant;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Db;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.module.*;
import com.sixmac.police.service.AdminRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AdminRoleController
 * 2018-09-26 11:15:35
 * @author Blade
 */
@Controller
@RequestMapping("/admin/home")
public class AdminHomeController extends BaseController {
	private static String CODE = "adminRole";
	private static String PREFIX = "t_admin_role";
	private static String LIST_SOURCE = "adminRole.list";
	private static String BASE_PATH = "/police/";
	
	@Autowired
	AdminRoleService service;
	
	@RequestMapping(KEY_MAIN)
	public String index(ModelMap mm) {
		Blade.create(TenantRoom.class).findFirstBy(" status is not null",null);
		AdminUser user = (AdminUser) getRequest().getSession().getAttribute(Constant.SESSION_ADMIN_USER);
		if(user == null){
			return redirect(Configue.getBaseDomain() + "/server/admin/login");
		}
		mm.put("code", CODE);
		mm.put("time",new Date());
		mm.put("user",user);
		//今日新增房东
		List<Landlord> landlord = Blade.create(Landlord.class).findBy("to_days(createDate) = to_days(now())",null);
		//今日新增房客
		List<Tenant> tenants = Blade.create(Tenant.class).findBy("to_days(createDate) = to_days(now())",null);
		//今日新增房屋
		List<Room> rooms = Blade.create(Room.class).findBy("to_days(createDate) = to_days(now())",null);
		//今日新增密钥申请
		List<TenantRoom> tenantRooms = Blade.create(TenantRoom.class).findBy("to_days(createDate) = to_days(now())",null);
		//今日新增居住证申请
		List<TenantLive> tenantLives = Blade.create(TenantLive.class).findBy("to_days(createDate) = to_days(now())",null);

		int countRoom =  Db.queryInt("SELECT COUNT(*) from t_room",null);

		int countlandlord = Db.queryInt("SELECT COUNT(*) from t_landlord",null);
		int countTenantRoom = Db.queryInt("SELECT COUNT(*) from  t_room r LEFT JOIN (SELECT * from t_tenant_room where `status` = 1 GROUP BY roomId) tr ON r.id = tr.roomId",null);
		int countTenant = Db.queryInt("SELECT COUNT(*) from  t_tenant r LEFT JOIN (SELECT * from t_tenant_room where `status` = 1 GROUP BY tenantId) tr ON r.id = tr.tenantId where tr.id is not null",null);
		int countsTenant = Db.queryInt("SELECT COUNT(*) from (SELECT * from t_tenant_live where `status` = 2 GROUP BY tenantId) alls",null);
		Map<String, Object> counts = Db.selectOne("SELECT SUM(if(r.sex = 1,1,0)) man,SUM(if(r.sex = 2,1,0)) woman from  t_tenant r LEFT JOIN (SELECT * from t_tenant_room where `status` = 1 GROUP BY tenantId) tr ON r.id = tr.tenantId where tr.id is not null",null);
		Map<String, Object> ages = Db.selectOne("SELECT  SUM(if(r.idCard < '1980',1,0)) one,SUM(if(substring(r.idCard,7,4) < '1985' and substring(r.idCard,7,4) >= '1980' ,1,0)) two,SUM(if(substring(r.idCard,7,4) < '1990' and substring(r.idCard,7,4) >= '1985' ,1,0)) three,SUM(if(substring(r.idCard,7,4) < '1995' and substring(r.idCard,7,4) >= '1990' ,1,0)) four,SUM(if(substring(r.idCard,7,4) >= '1995' ,1,0)) fix from  t_tenant r LEFT JOIN (SELECT * from t_tenant_room where `status` = 1 GROUP BY tenantId) tr ON r.id = tr.tenantId where tr.id is not null and r.idCard IS not null",null);
		List<Map> opens = Db.selectList("SELECT count(*) n,cast(DATE_FORMAT(o.createDate,\"%d\") as SIGNED INTEGER) days from t_open_history o WHERE DATE_FORMAT(o.createDate,\"%Y%m%d\")>=CONCAT(DATE_FORMAT(now(),\"%Y%m\"),'01') and DATE_FORMAT(o.createDate,\"%Y%m%d\")<=CONCAT(DATE_FORMAT(now(),\"%Y%m\"),'31')GROUP BY DATE_FORMAT(o.createDate,\"%Y%m%d\")",null);
		List<Map> users = Db.selectList("SELECT count(*) n, cast( DATE_FORMAT(o.createDate, \"%d\") AS SIGNED INTEGER ) days\n" +
				"FROM ( SELECT c.*,tr.createDate FROM t_contact c LEFT JOIN t_tenant_room tr ON c.tenantRoomId = tr.id WHERE\n" +
				"\t\t\tc.`status` IS NOT NULL GROUP BY c.tentantId ) o WHERE\n" +
				"\tDATE_FORMAT(o.createDate, \"%Y%m%d\") >= CONCAT(\n" +
				"\t\tDATE_FORMAT(now(), \"%Y%m\"),\n" +
				"\t\t'01'\n" +
				"\t)\n" +
				"AND DATE_FORMAT(o.createDate, \"%Y%m%d\") <= CONCAT(\n" +
				"\tDATE_FORMAT(now(), \"%Y%m\"),\n" +
				"\t'31'\n" +
				")\n" +
				"AND o.status = 0\n" +
				"GROUP BY\n" +
				"\tDATE_FORMAT(o.createDate, \"%Y%m%d\")",null);
		List<Map> users2 = Db.selectList("SELECT count(*) n, cast( DATE_FORMAT(o.createDate, \"%d\") AS SIGNED INTEGER ) days\n" +
				"FROM ( SELECT c.*,tr.createDate FROM t_contact c LEFT JOIN t_tenant_room tr ON c.tenantRoomId = tr.id WHERE\n" +
				"\t\t\tc.`status` IS NOT NULL GROUP BY c.tentantId ) o WHERE\n" +
				"\tDATE_FORMAT(o.outTime, \"%Y%m%d\") >= CONCAT(\n" +
				"\t\tDATE_FORMAT(now(), \"%Y%m\"),\n" +
				"\t\t'01'\n" +
				"\t)\n" +
				"AND DATE_FORMAT(o.outTime, \"%Y%m%d\") <= CONCAT(\n" +
				"\tDATE_FORMAT(now(), \"%Y%m\"),\n" +
				"\t'31'\n" +
				")\n" +
				"AND o.status = 1\n" +
				"GROUP BY\n" +
				"\tDATE_FORMAT(o.outTime, \"%Y%m%d\")",null);
		List<Map> users3 = Db.selectList("SELECT\n" +
				"\tcount(*) n,\n" +
				"\tcast(\n" +
				"\t\tDATE_FORMAT(o.createDate, \"%m\") AS SIGNED INTEGER\n" +
				"\t) days\n" +
				"FROM\n" +
				"\t(\n" +
				"\t\tSELECT\n" +
				"\t\t\tc.*, tr.createDate\n" +
				"\t\tFROM\n" +
				"\t\t\tt_contact c\n" +
				"\t\tLEFT JOIN t_tenant_room tr ON c.tenantRoomId = tr.id\n" +
				"\t\tWHERE\n" +
				"\t\t\tc.`status` IS NOT NULL\n" +
				"\t\tGROUP BY\n" +
				"\t\t\tc.tentantId\n" +
				"\t) o\n" +
				"WHERE\n" +
				"\tDATE_FORMAT(o.createDate, \"%Y%m\") >= CONCAT(\n" +
				"\t\tDATE_FORMAT(now(), \"%Y\"),\n" +
				"\t\t'01'\n" +
				"\t)\n" +
				"AND DATE_FORMAT(o.createDate, \"%Y%m\") <= CONCAT(\n" +
				"\tDATE_FORMAT(now(), \"%Y\"),\n" +
				"\t'12'\n" +
				")\n" +
				"AND o. STATUS = 0\n" +
				"GROUP BY\n" +
				"\tcast(\n" +
				"\t\tDATE_FORMAT(o.createDate, \"%m\") AS SIGNED INTEGER\n" +
				"\t)",null);

		List<Map> users4 = Db.selectList("SELECT\n" +
				"\tSUM(if(o.id is not null,1,0)) n,\n" +
				"\tcast(\n" +
				"\t\tDATE_FORMAT(o.createDate, \"%m\") AS SIGNED INTEGER\n" +
				"\t) days\n" +
				"FROM\n" +
				"\t(\n" +
				"\t\tSELECT\n" +
				"\t\t\tc.*, tr.createDate\n" +
				"\t\tFROM\n" +
				"\t\t\tt_contact c\n" +
				"\t\tLEFT JOIN t_tenant_room tr ON c.tenantRoomId = tr.id\n" +
				"\t\tWHERE\n" +
				"\t\t\tc.`status` IS NOT NULL\n" +
				"\t\tGROUP BY\n" +
				"\t\t\tc.tentantId\n" +
				"\t) o\n" +
				"WHERE\n" +
				"\tDATE_FORMAT(o.outTime, \"%Y%m\") >= CONCAT(\n" +
				"\t\tDATE_FORMAT(now(), \"%Y\"),\n" +
				"\t\t'01'\n" +
				"\t)\n" +
				"AND DATE_FORMAT(o.outTime, \"%Y%m\") <= CONCAT(\n" +
				"\tDATE_FORMAT(now(), \"%Y\"),\n" +
				"\t'12'\n" +
				")\n" +
				"AND o. STATUS = 1\n" +
				"GROUP BY\n" +
				"\tcast(\n" +
				"\t\tDATE_FORMAT(o.outTime, \"%m\") AS SIGNED INTEGER\n" +
				"\t)",null);

		HashMap<String,Integer> open = new HashMap<>();
		for (int i=1;i<=31;i++){
			open.put(i+"",0);
			for (Map map:opens) {
				if (Integer.valueOf(map.get("days").toString()) == i){
					open.put(i+"",Integer.valueOf(map.get("n").toString()));
				}
			}
		}

		HashMap<String,Integer> tenantUser = new HashMap<>();
		for (int i=1;i<=31;i++){
			tenantUser.put(i+"",0);
			for (Map map:users) {
				if (Integer.valueOf(map.get("days").toString()) == i){
					tenantUser.put(i+"",Integer.valueOf(map.get("n").toString()));
				}
			}
		}
		HashMap<String,Integer> tenantUser2 = new HashMap<>();
		for (int i=1;i<=31;i++){
			tenantUser2.put(i+"",0);
			for (Map map:users2) {
				if (Integer.valueOf(map.get("days").toString()) == i){
					tenantUser2.put(i+"",Integer.valueOf(map.get("n").toString()));
				}
			}
		}

		HashMap<String,Integer> tenantUser3 = new HashMap<>();
		for (int i=1;i<=12;i++){
			tenantUser3.put(i+"",0);
			for (Map map:users3) {
				if (Integer.valueOf(map.get("days").toString()) == i){
					tenantUser3.put(i+"",Integer.valueOf(map.get("n").toString()));
				}
			}
		}

		HashMap<String,Integer> tenantUser4 = new HashMap<>();
		for (int i=1;i<=12;i++){
			tenantUser4.put(i+"",0);
			for (Map map:users4) {
				if (Integer.valueOf(map.get("days").toString()) == i){
					tenantUser4.put(i+"",Integer.valueOf(map.get("n").toString()));
				}
			}
		}

		Integer man = Integer.valueOf(counts.get("man").toString());
		Integer woman = Integer.valueOf(counts.get("woman").toString());
		double mans = man*100.00/(man+woman);
		double womans = woman*100.00/(man+woman);
		mm.put("today_Landlord",landlord.size());
		mm.put("today_tenant",tenants.size());
		mm.put("today_room",rooms.size());
		mm.put("today_tenantRoom",tenantRooms.size());
		mm.put("today_tenantLive",tenantLives.size());

		mm.put("countlandlord",countlandlord);
		mm.put("countTenantRoom",countTenantRoom);
		mm.put("countTenant",countTenant);
		mm.put("countRoom",countRoom);
		mm.put("countsTenant",countsTenant);
		mm.put("man",mans);
		mm.put("woman",womans);
		Integer one = Integer.valueOf(ages.get("one").toString());
		Integer two = Integer.valueOf(ages.get("two").toString());
		Integer three = Integer.valueOf(ages.get("three").toString());
		Integer four = Integer.valueOf(ages.get("four").toString());
		Integer fix = Integer.valueOf(ages.get("fix").toString());
		mm.put("one",one*100.00/(one+two+three+four+fix));
		mm.put("two",two*100.00/(one+two+three+four+fix));
		mm.put("three",three*100.00/(one+two+three+four+fix));
		mm.put("four",four*100.00/(one+two+three+four+fix));
		mm.put("fix",fix*100.00/(one+two+three+four+fix));
		mm.put("open",open);
		mm.put("tenantUser",tenantUser);
		mm.put("tenantUser2",tenantUser2);
		mm.put("tenantUser3",tenantUser3);
		mm.put("tenantUser4",tenantUser4);

		return BASE_PATH + "homepage.html";
	}

	@RequestMapping(KEY_ADD)
	public String add(ModelMap mm) {
		mm.put("code", CODE);
		return BASE_PATH + "adminRole_add.html";
	}

	@RequestMapping(KEY_EDIT + "/{id}")
	public String edit(@PathVariable Integer id, ModelMap mm) {
		AdminRole adminRole = service.findById(id);
		mm.put("model", JsonKit.toJson(adminRole));
		mm.put("id", id);
		mm.put("code", CODE);
		return BASE_PATH + "adminRole_edit.html";
	}

	@RequestMapping(KEY_VIEW + "/{id}")
	public String view(@PathVariable Integer id, ModelMap mm) {
		AdminRole adminRole = service.findById(id);
		mm.put("model", JsonKit.toJson(adminRole));
		mm.put("id", id);
		mm.put("code", CODE);
		return BASE_PATH + "adminRole_view.html";
	}

	@ResponseBody
	@RequestMapping(KEY_LIST)
	public Object list() {
		Object grid = paginate(LIST_SOURCE);
		return grid;
	}

	@ResponseBody
	@RequestMapping(KEY_SAVE)
	public AjaxResult save() {
		AdminRole adminRole = mapping(PREFIX, AdminRole.class);
		boolean temp = service.save(adminRole);
		if (temp) {
			return success(SAVE_SUCCESS_MSG);
		} else {
			return error(SAVE_FAIL_MSG);
		}
	}

	@ResponseBody
	@RequestMapping(KEY_UPDATE)
	public AjaxResult update() {
		AdminRole adminRole = mapping(PREFIX, AdminRole.class);
		boolean temp = service.update(adminRole);
		if (temp) {
			return success(UPDATE_SUCCESS_MSG);
		} else {
			return error(UPDATE_FAIL_MSG);
		}
	}

	@ResponseBody
	@RequestMapping(KEY_REMOVE)
	public AjaxResult remove(@RequestParam String ids) {
		int cnt = service.deleteByIds(ids);
		if (cnt > 0) {
			return success(DEL_SUCCESS_MSG);
		} else {
			return error(DEL_FAIL_MSG);
		}
	}

}
